import { ref, reactive } from 'vue';
import { ElNotification } from 'element-plus';
import { addUserRoles } from '@/axios/api/acl/user';
import { getRoles, addRole, getAllMenus } from '@/axios/api/acl/role';

export default function () {
    interface rolesType {
        role_id: number;
        role_name: string;
    }

    // 所有角色
    const allRoles = ref<rolesType[]>([]);
    // 所有角色名称
    const roleNames = ref<string[]>([]);

    // 已选择角色
    const selectedRoles = ref<string[]>([]);

    // 用户列表
    const tableData = ref([]);

    let roleadd_data = reactive({
        id: '',
        rolename: '',
    })
    // 抽屉
    let dialog = ref(false); // 是否显示抽屉

    // 搜索框
    let username = ref('');

    // 当前页数
    let currentPage4 = ref(1);
    // 每页显示条数
    let pageSize4 = ref(30);
    // 总条数
    let total4 = ref(0);
    // 获取用户列表
    const usegetRoles = async () => {
        try {
            let res: any = await getRoles(currentPage4.value, pageSize4.value);
            tableData.value = res.data;
            total4.value = res.total;
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }
    // 每页显示条目个数改变时触发
    const handleSizeChange = () => {
        currentPage4.value = 1;
        usegetRoles();
    }
    // 当前页数改变时触发
    const handleCurrentChange = () => {
        usegetRoles();
    }

    // 搜索
    const handleSearch = () => {
        console.log(username.value);
    }
    // 重置
    const handleReset = () => {
        username.value = '';
    }

    // 编辑
    const handleEdit = () => {
        // dialog.value = true;
        ElNotification({
            title: 'Error',
            message: '该功能暂未实现',
            type: 'error',
        })
    }
    // 删除
    const handleDelete = async (_index: number) => {
        ElNotification({
            title: 'Error',
            message: '该功能暂未实现',
            type: 'error',
        })
    }

    // 添加角色
    const handleAdd = () => {
        dialog.value = true;
    }
    // 添加角色提交
    const handleAddsubmit = async () => {
        try {
            let res: any = await addRole(roleadd_data);
            ElNotification({
                title: 'Success',
                message: res.msg,
                type: 'success',
            });
            roleadd_data.id = '';
            roleadd_data.rolename = '';
            dialog.value = false;
            currentPage4.value = 1;
            usegetRoles();
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }
    // 批量删除
    const handleDeleteAll = () => {
        console.log('delete all');

    }

    // 抽屉表单校验

    const rolename1 = (_rule: any, value: any, callback: any) => {
        if (/^\d+$/.test(value)) {
            callback(new Error('角色名称不能为纯数字'))
        } else if (value === '') {
            callback(new Error('请输入角色名称'))
        } else {
            callback() //通过
        }
    }
    const rolename2 = (_rule: any, value: any, callback: any) => {
        // 判断value是否在tableData中
        let flag = false;
        tableData.value.forEach((item: any) => {
            if (item.role_name.toLowerCase() === value.toLowerCase()) {
                flag = true;
                return;
            }
        });

        if (flag) {
            callback(new Error('角色名称已存在'))
        } else {
            callback() //通过
        }
    }

    const rules = {
        rolename: [
            { validator: rolename1, trigger: 'change' },
            { validator: rolename2, trigger: 'blur' }
        ]
    }

    // 分配角色
    interface roleType {
        UserID: number;
        full_name: string;
        roles: number[];
    }
    let role_data = reactive<roleType>({
        UserID: 0,
        full_name: '',
        roles: []
    })

    let dialog_role = ref(false) // 是否显示分配角色抽屉




    const checkAll = ref(false) // 全选
    const isIndeterminate = ref(true) // 半选


    // 全选/半选
    const handleCheckAllChange = (val: boolean) => {
        selectedRoles.value = val ? roleNames.value : []
        isIndeterminate.value = false
    }
    // 已选中角色
    const handleCheckedCitiesChange = (value: string[]) => {
        const checkedCount = value.length
        checkAll.value = checkedCount === roleNames.value.length
        isIndeterminate.value = checkedCount > 0 && checkedCount < roleNames.value.length
    }

    // 提交分配角色
    const submitRole = async () => {
        if (selectedRoles.value.length === 0) {
            ElNotification({
                title: 'Error',
                message: '请选择角色',
                type: 'error',
            })
            return;
        }
        role_data.roles = selectedRoles.value.map(roleName => {
            let role: any = allRoles.value.find(item => item.role_name === roleName);
            return role.role_id;
        });

        try {
            let res = await addUserRoles(role_data)
            ElNotification({
                title: 'Success',
                message: res.msg,
                type: 'success',
            });
            dialog_role.value = false;
            currentPage4.value = 1;
            usegetRoles();
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }


    let acldrawer = ref(false) // 是否显示分配权限抽屉
    let menuArr = ref<any>([]) // 角色拥有的权限
    let selectArr = ref<number[]>([]) // 已选中的权限
    const role_id = ref(0) // 角色id

    // 弹出分配权限
    const handleRole = async (row: any) => {
        menuArr.value = []
        selectArr.value = []
        role_id.value = row.role_id;
        acldrawer.value = true;
        try {
            let res: any = await getAllMenus(row.role_id)
            menuArr.value.push(JSON.parse(res.data))
            selectArr.value = filterSelectArr(menuArr.value, []);
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }

    const filterSelectArr = (allData: any, initArr: any) => {
        allData.forEach((item: any) => {
            if (item.has_permission) {
                initArr.push(item.acl_id);
            }
            if (item.children && item.children.length > 0) {
                filterSelectArr(item.children, initArr);
            }
        })

        return initArr;
    }

    const defaultProps = {
        children: 'children',
        label: 'title',
    }



    return {
        tableData,
        roleadd_data,
        dialog,
        username,
        currentPage4,
        pageSize4,
        total4,
        rules,
        role_data,
        dialog_role,
        allRoles,
        roleNames,
        selectedRoles,
        checkAll,
        isIndeterminate,
        acldrawer,
        handleSizeChange,
        handleCurrentChange,
        handleSearch,
        handleReset,
        handleRole,
        handleEdit,
        handleDelete,
        handleAdd,
        handleDeleteAll,
        usegetRoles,
        handleAddsubmit,
        handleCheckAllChange,
        handleCheckedCitiesChange,
        submitRole,
        menuArr,
        selectArr,
        defaultProps,
        role_id
    }
}